package com.qdu.spring.blog.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

/**
*功能（配置多数据源）
 */

@Configuration //注册到SpringBoot容器中
@MapperScan(basePackages = "com.qdu.spring.blog.mapper.test1",sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config {

    /**
     * @methodDesc:功能描述：配置数据库
     * @author:lcs
     * @param:@return
     * @returnType:@return DataSource
     */
    //@Bean表示将注入到Spring容器中去
    @Bean(name = "test1DataSource")
    //当系统中有多个数据源时，必须有一个数据源为主数据源，使用@Primary修饰。
    @Qualifier("test1DataSource")
    //表示以spring.datasource.test1开头去application.yml中去读取jdbc详细信息
    @ConfigurationProperties(prefix="spring.datasource.test1" )
    @Primary
    public DataSource test1DataSource() {
        return DataSourceBuilder.create().build();
    }


    /**
     * @methodDesc:功能描述：事务管理
     * @author:lcs
     * @param:@param DataSource
     * @param:@return
     * @param：@throws Exception
     * @returnType:@return DataSource
     */
    //配置事务
    @Bean(name = "test1TransactionManager")
    @Primary
    public DataSourceTransactionManager test1TransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * @methodDesc:功能描述：配置会话工厂
     * @author:lcs
     * @param:@return DataSource
     * @returnType:@return
     * @returnType：@throws Exception SqlSessionFactory
     */
    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //扫描mapper.xml
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/test1/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "test1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate test1SqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
